package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.yipaiju.domain.WXOpenid;
import com.ruoyi.yipaiju.domain.WechatLogin;
import com.ruoyi.yipaiju.service.IWechatService;
import com.ruoyi.yipaiju.service.IXcxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 微信登录授权Controller
 * @author liuwp
 * @date 2023-02-28
 */
@RestController
@RequestMapping("/authenticate")
public class AuthenticateController extends BaseController {

    @Autowired
    private IWechatService wechatService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IXcxUserService xcxUserService;

    /**
     * 微信登录授权
     * @param wechatLogin
     * @return
     */
    @Anonymous
    @PostMapping("/code")
    public ApiResult code(@RequestBody WechatLogin wechatLogin)
    {
        try {
            WXOpenid wxOpenid = wechatService.getWXOpenid(wechatLogin.getCode());
            if (wxOpenid.getErrcode() == null){
                XcxUser xcxUser = xcxUserService.xcxUserLogin(wxOpenid);
                if (StringUtils.isNotEmpty(xcxUser.getPhone())){
                    xcxUser.setPhone_is_verified(true);
                }
                // TODO 角色不知道咋弄，不知道要啥东西  闹腾
                xcxUser.setSessionKey(wxOpenid.getSession_key());
                xcxUser.setLoginTime(new Date());
                xcxUser = xcxUserService.getXcxUserLogin(xcxUser);
                LoginUser loginUser = new LoginUser(xcxUser.getId(), null, xcxUser, null);
                String token = tokenService.createToken(loginUser);
                xcxUser.setAccess(token);
//                return ApiResult.success(ImmutableMap.of("access", token, "refresh", ""));
                return ApiResult.success(xcxUser);
            }else {
                return ApiResult.error(wxOpenid.getErrmsg());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ApiResult.error();
    }

}
